const dayjs = require('dayjs');
const mongoose = require('../config/db');
const { Schema } = mongoose;
const Counter = require('./counter');

const UserSchema = new Schema({
  user_id: {
    type: Number,
    unique: true,
    description: '用户id'
  },
  username: {
    type: String,
    required: true,
    trim: true,
    default: '',
    description: '用户名'
  },
  password: {
    type: String,
    required: false,
    default: '',
    description: '密码'
  },
  email: {
    type: String,
    required: false,
    trim: true,
    default: '',
    description: '邮箱'
  },
  phone_number: {
    type: Number,
    required: false,
    trim: true,
    default: null,
    description: '电话号码'
  },
  created_at: {
    type: String,
    required: false,
    trim: true,
    default: dayjs().format('YYYY-MM-DD HH:mm:ss'),
    description: '创建时间'
  },
  updated_at: {
    type: String,
    required: false,
    trim: true,
    default: dayjs().format('YYYY-MM-DD HH:mm:ss'),
    description: '最后更新时间'
  },
  status: {
    type: Number,
    required: false,
    trim: true,
    enum: [0, 1], // 0:禁用 1:启用
    default: 1,
    description: '账户状态'
  },
  role: {
    type: String,
    required: false,
    trim: true,
    default: '',
    description: '角色'
  },
  avatar: {
    type: String,
    required: false,
    trim: true,
    default: '',
    description: '用户头像'
  },
  last_login: {
    type: Number,
    required: false,
    trim: true,
    default: 0,
    description: '最后登录时间'
  },
  gender: {
    type: Number,
    required: false,
    trim: true,
    enum: [0, 1, 2], // 0:未知 1:男 2:女
    default: 0,
    description: '性别'
  },
  address: {
    type: String,
    required: false,
    trim: true,
    default: '',
    description: '地址'
  },
  country: {
    type: String,
    required: false,
    trim: true,
    default: '',
    description: '国家'
  },
  language: {
    type: String,
    required: false,
    trim: true,
    default: 'zh-CN',
    description: '语言'
  },
  preferences: {
    type: String,
    required: false,
    trim: true,
    default: '{}',
    description: '偏好'
  },
  social: {
    type: String,
    required: false,
    trim: true,
    default: '{}',
    description: '社交平台'
  }
})

// Add pre-save middleware to auto-increment user_id
UserSchema.pre('save', async function(next) {
  if (this.isNew) {
    try {
      const counter = await Counter.findByIdAndUpdate(
        { _id: 'user_id' },
        { $inc: { seq: 1 } },
        { new: true, upsert: true }
      );
      this.user_id = counter.seq;
      next();
    } catch (error) {
      next(error);
    }
  } else {
    next();
  }
});

// 更新时间
UserSchema.pre('updateOne', async function(next) {
  this.set({ updated_at: dayjs().format('YYYY-MM-DD HH:mm:ss') });
  next();
});

/**
 * name: string 模型名称
 * schema?: mongoose.Schema<...> | undefined
 * collection?: string 集合名称
 */
const UserModel = mongoose.model('user', UserSchema, 'user');

module.exports = UserModel;
